﻿<?php

class Book
{

//book data
	public $fileName;
	public $pureFileName;
	public $fileSize;
	public $flibustaBookID;
	public $book_title;
	public $authorName = array() ;
	public $translatorName = array() ;
	public $genre = array();
	public $annotation;
	public $date;
	public $coverpage;
	public $lang;
	public $srcLang;
	public $keywords;
	public $sequence = array();
	public $binary;
	public $bookType;
	public $status;
	public $body;

//publisher data
	public $publisherBookName;
	public $publisherPublisher;
	public $publisherCity;
	public $publisherYear;
	public $publisherISBN;

	public $FB_LOG = array();




	public function readDataFromFile($filename)
	{
		$this->bookType = "fb2";
		$this->fileName = $filename;

		$this->pureFileName = basename($this->fileName) ;
		// get file size in bytes
		$this->fileSize = filesize($this->fileName);
        //Создаем XML документ
		$fb2XML = new DOMDocument();
        //Отключаем проверку ошибок
		$fb2XML->strictErrorChecking = true; $fb2XML->recover = true;

        // GZip check
		if (strcmp(mb_substr($this->fileName,-3,3),".gz") == 0)
        {
            $currentBookData = gzfile($this->fileName);

            //$string = mb_convert_encoding($string, 'utf-8', mb_detect_encoding($string));

            if (!mb_detect_encoding($currentBookData[0]))
            {
            	$this->status="error";
            	return;
            }

            $currentBookData = implode($currentBookData);

           // might be deleted
	            if (mb_strlen($currentBookData) < 20 )
	            {
	            	$this->status="error";
	            	return;
	            }
	            else
	            {
	            	$this->status="good";
	            }
            $loadedFB2 =  $fb2XML->loadXML($currentBookData,LIBXML_NOERROR);

            //check if file name - is number - Yes - leave it like flibustaBookID / Else - NULL
            $this->flibustaBookID = mb_substr($this->pureFileName,0,-7);
            	if (!is_numeric($this->flibustaBookID))
            	{
            		$this->flibustaBookID = '';
            	}

        }
        else
        {
//Загружаем содиржоме файла
    		$loadedFB2 = $fb2XML->load($this->fileName,LIBXML_NOERROR);
    		//check if file name - is number - Yes - leave it like flibustaBookID / Else - NULL
    		$this->flibustaBookID = mb_substr($this->pureFileName,0,-4);
    		if (!is_numeric($this->flibustaBookID))
    		{
    			$this->flibustaBookID = '';
    		}

        }


			if (!$loadedFB2)
			{
				$this->FB_LOG[] = "FB2 error: file load error" ;
			}


			$encoding = $fb2XML->encoding;

//Получаем содержимое секции <description>
		$description = $fb2XML->getElementsByTagName('description')->item(0);
			if (!$description)
			{
				$this->FB_LOG[] = "FB2 error: description section not found" ;
			}


//Получаем название книги
		// TITLE (title_info)
		$title_info = $description->getElementsByTagName('title-info')->item(0);


		if (isset($title_info->getElementsByTagName('book-title')->item(0)->nodeValue))
		{
			$this->book_title = trim($title_info->getElementsByTagName('book-title')->item(0)->nodeValue);
		}
		else
		{
			$this->FB_LOG[] = "FB2 error: Book title not found" ;
		}



//получаем "файл нэйм" обложки
		// Specs sais it's always starts with # so drop it.

		// have to be fixed  !==4 not really correct solution!
		if (($title_info->getElementsByTagName('coverpage')->length ) !== 0 )
		{
			if ($title_info->getElementsByTagName('coverpage')->item(0)->childNodes->length > 1)
			{
				$coverPageFileName = ltrim($title_info->getElementsByTagName('coverpage')->item(0)->getElementsByTagName('image')->item(0)->attributes->item(0)->nodeValue, "#");
			}
			else
			{
				$coverPageFileName="None";
			}
		}
		else
		{
			$coverPageFileName="None";
		}

		//$pureFileName;

// вернуть тело книги (сам текст)

	$this->body = $fb2XML->getElementsByTagName('body')->item(0)->nodeValue ;



//Получаем обложку, картинку
$imageCounter = 0;

if ( ($fb2XML->getElementsByTagName('binary')->length) < 1 )
{
	$this->binary = "default.jpg";
}

		foreach ($fb2XML->getElementsByTagName('binary') as $currentPic)
		{
			foreach ($currentPic->attributes as $curAttr)
			{
				//search for attribute = id in case to found cover image that was pointed from <coverpage> tag
				if (strcasecmp($curAttr->nodeName,"id") == 0 )
				{
					// check if current binary, id is cover page.
					if (strcasecmp($curAttr->nodeValue, $coverPageFileName) == 0 )
					{
						$this->binary = $currentPic->nodeValue;
					}
					else
					{
						$this->binary = "default.jpg";
					}

				}

			}
		$imageCounter++;
		}
		if (($this->binary == "default.jpg") && ($imageCounter > 0) ) { $this->binary = $fb2XML->getElementsByTagName('binary')->item(0)->nodeValue;}




//Получаем список жанров, к которым относится книга
// GENRE
		$genre_list = $title_info->getElementsByTagName('genre');
		if ($genre_list->length==0)
		{
			$this->FB_LOG[] = "FB2 error: genre not found" ;

		}
		else
		foreach ($genre_list as $currentGenre)
		{
			//Помещаем список жанров в массив
			$this->genre[] = $currentGenre->nodeValue;
		}

//Получаем название серии и номер
//SEQUENCE
		$sequenceList = $description->getElementsByTagName('sequence');

		if (!$sequenceList)
		{
			$this->$sequence[0]['name']="" ;
			$this->$sequence[0]['number']="" ;
			$this->FB_LOG[] = "FB2 warning: sequence not found" ;
		}
		else
		{
			$counter=0;
			foreach ($sequenceList as $currentSequence)
			{
				//Помещаем список серий в массив [порядковый номер][название]="название серии" / [порядковый номер][номер]="номер книги в серии"
				$this->sequence[$counter]['name'] = $currentSequence->getAttribute('name');
				$this->sequence[$counter]['number'] = $currentSequence->getAttribute('number');
				$counter++;
			}
		}

//Получаем список авторов.
//AUTHOR
		$authors_list = $title_info->getElementsByTagName('author');
		if ($authors_list->length==0)
		{
			$this->FB_LOG[] = "FB2 error: author not found" ;
		}
		else
		{
			$counter=0;

			foreach ($authors_list as $currentAuthor)
			{
				$this->authorName[$counter]['first-name'] =  (isset( $currentAuthor->getElementsByTagName('first-name')->item(0)->nodeValue) ?  $currentAuthor->getElementsByTagName('first-name')->item(0)->nodeValue : "");
				$this->authorName[$counter]['middle-name'] =  (isset( $currentAuthor->getElementsByTagName('middle-name')->item(0)->nodeValue) ?  $currentAuthor->getElementsByTagName('middle-name')->item(0)->nodeValue : "");
				$this->authorName[$counter]['last-name'] =  (isset( $currentAuthor->getElementsByTagName('last-name')->item(0)->nodeValue) ?  $currentAuthor->getElementsByTagName('last-name')->item(0)->nodeValue : "");
				$this->authorName[$counter]['nickname'] = (isset($currentAuthor->getElementsByTagName('nickname')->item(0)->nodeValue) ? $currentAuthor->getElementsByTagName('nickname')->item(0)->nodeValue : "" ) ;
				$this->authorName[$counter]['email'] =  (isset($currentAuthor->getElementsByTagName('email')->item(0)->nodeValue) ? $currentAuthor->getElementsByTagName('email')->item(0)->nodeValue : "" ) ;
				$counter++;
			}
		}

//Получаем список переводчиков.
//TRANSLATOR
		$translators_list = $title_info->getElementsByTagName('translator');
		if ($translators_list->length==0)
		{
			$this->FB_LOG[] = "FB2 warning: translator not found" ;
		}
		else
		{
			$counter=0;
			foreach ($translators_list as $currentTranslator)
			{
				$this->translatorName[$counter]['first-name'] = (isset( $currentTranslator->getElementsByTagName('first-name')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('first-name')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['middle-name'] = (isset( $currentTranslator->getElementsByTagName('middle-name')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('middle-name')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['last-name'] = (isset( $currentTranslator->getElementsByTagName('last-name')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('last-name')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['nickname'] = (isset( $currentTranslator->getElementsByTagName('nickname')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('nickname')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['email'] = (isset( $currentTranslator->getElementsByTagName('email')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('email')->item(0)->nodeValue : "") ;
				$counter++;

			}
		}

		//Получаем анотацию.
//ANNOTATION
		if ($title_info->getElementsByTagName('annotation')->length==0)
		{
			$this->FB_LOG[] = "FB2 warning: annotation not found" ;
			$this->annotation = "No annotation";
		}
		else
		{
			$this->annotation = trim($title_info->getElementsByTagName('annotation')->item(0)->nodeValue," \t\n\r\0\x0B");
			if (mb_strlen(trim($this->annotation)) < 1)
			{
				$this->annotation = "No annotation";
			}
		}



		//Получаем дату.
//DATE
		if ($title_info->getElementsByTagName('date')->length==0)
		{
			$this->FB_LOG[] = "FB2 warning: date not found" ;
		}
		else
		{
			$this->date = $title_info->getElementsByTagName('date')->item(0)->nodeValue;
		}

		//Получаем язык.
//LANGUAGE
		if ($title_info->getElementsByTagName('lang')->length==0)
		{
			$this->FB_LOG[] = "FB2 warning: language not found" ;
		}
		else
		{
			$this->lang = $title_info->getElementsByTagName('lang')->item(0)->nodeValue;
		}

		//Получаем язык оригинала.
//SOURCE_LANGUAGE
		if ($title_info->getElementsByTagName('src-lang')->length==0)
		{
			$this->FB_LOG[] = "FB2 warning: language of source not found" ;
		}
		else
		{
			$this->srcLang = $title_info->getElementsByTagName('src-lang')->item(0)->nodeValue;
		}

		//Получаем keywords.
//KEYWORDS
		if ($title_info->getElementsByTagName('keywords')->length==0)
		{
			$this->FB_LOG[] = "FB2 warning: keywords not found" ;
		}
		else
		{
			$this->keywords = $title_info->getElementsByTagName('keywords')->item(0)->nodeValue;
		}


// PUBLISH(ER)-INFO

		$publish_info = $description->getElementsByTagName('publish-info')->item(0);

		if (!$publish_info)
		{
			$this->FB_LOG[] = "FB2 warning: publisher info was found";
		}
		else
		{
			$this->publisherBookName 	= (isset($publish_info->getElementsByTagName('book-name')->item(0)->nodeValue) ? $publish_info->getElementsByTagName('book-name')->item(0)->nodeValue : "") ;
			$this->publisherPublisher 	= (isset($publish_info->getElementsByTagName('publisher')->item(0)->nodeValue) ? $publish_info->getElementsByTagName('publisher')->item(0)->nodeValue : "") ;
			$this->publisherCity 		= (isset($publish_info->getElementsByTagName('city')->item(0)->nodeValue) ? $publish_info->getElementsByTagName('city')->item(0)->nodeValue : "") ;
			$this->publisherYear 		= (isset($publish_info->getElementsByTagName('year')->item(0)->nodeValue) ? $publish_info->getElementsByTagName('year')->item(0)->nodeValue : "") ;
			$this->publisherISBN 		= (isset($publish_info->getElementsByTagName('isbn')->item(0)->nodeValue) ? $publish_info->getElementsByTagName('isbn')->item(0)->nodeValue : "") ;
		}
}


public function readDataFromEPUB($filename)
{

	$this->bookType = "epub";
	$this->fileName = $filename;

	$this->pureFileName = basename($this->fileName) ;
	// get file size in bytes
	$this->fileSize = filesize($this->fileName);


	// getting correct OPF file from META-INF/container.xml
	$LOAD_OPF_CONTAINER = simplexml_load_file('zip://'.$this->fileName.'#META-INF/container.xml');
	$OPF_filename= $LOAD_OPF_CONTAINER->rootfiles->rootfile->attributes()->{'full-path'}[0];


	$EPUB_metadata = simplexml_load_file('zip://'.$this->fileName.'#'.$OPF_filename);




	echo $EPUB_metadata->metadata->children('dc', true)->identifierz;

	echo $EPUB_metadata->metadata->children('dc', true)->title;
	echo $EPUB_metadata->metadata->children('dc', true)->creator;
	echo $EPUB_metadata->metadata->children('dc', true)->language;

	echo $EPUB_metadata->metadata->children('dc', true)->description;
	echo $EPUB_metadata->metadata->children('dc', true)->publisher;
	echo $EPUB_metadata->metadata->children('dc', true)->date;
	echo $EPUB_metadata->metadata->children('dc', true)->identifier;


}


}


?>
